package com.xyw.code.spingbootoath2demojdbc1.config;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xyw.code.spingbootoath2demojdbc1.mapper.SysUserMapper;
import com.xyw.code.spingbootoath2demojdbc1.model.PrexSecurityUser;
import com.xyw.code.spingbootoath2demojdbc1.model.SysUser;
import com.xyw.code.spingbootoath2demojdbc1.model.UserDetailsInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

/**
 * @Classname UserServiceDetail
 * @Description 用户身份验证
 * @Author 李号东 im.lihaodong@gmail.com
 * @Date 2019-03-19 16:55
 * @Version 1.0
 */
@Slf4j
@Service
public class PrexUserDetailsServiceImpl implements UserDetailsService  {

    @Autowired
    private SysUserMapper sysUserMapper;

    /**
     * 通过用户名查询用户
     *
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        LambdaQueryWrapper<SysUser> select = Wrappers.<SysUser>lambdaQuery()
                .select(SysUser::getUserId, SysUser::getUsername, SysUser::getPassword)
                .eq(SysUser::getUsername, username)
                .or()
                .eq(SysUser::getPhone, username)
                .or()
                .eq(SysUser::getUserId, username)
                .or()
                .eq(SysUser::getEmail, username);
        SysUser user = sysUserMapper.selectOne(select);
//        SysUser user = new SysUser();
        if (user==null) {
            log.debug("登录用户：" + username + " 不存在.");
            throw new UsernameNotFoundException("登录用户：" + username + " 不存在");
        }
        UserDetailsInfo userDetailsInfo = new UserDetailsInfo();
        // 权限集合
        Set<String> permissions = new HashSet<>();
        permissions.add("AMIND");
        // 角色集合
        userDetailsInfo.setSysUser(user);
        userDetailsInfo.setPermissions(permissions);
        Collection<? extends GrantedAuthority> authorities = AuthorityUtils.createAuthorityList(permissions.toArray(new String[0]));
        return new PrexSecurityUser(user.getUserId(), username, "{bcrypt}"+user.getPassword(), authorities);

    }
}
